package handlers

import (
	"context"
	"ourplansystem/server/ent"
	"ourplansystem/server/ent/qarecord"
	"ourplansystem/server/models"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
)

// QARecordHandler 情侣问答处理器
type QARecordHandler struct {
	client *ent.Client
}

// NewQARecordHandler 创建情侣问答处理器
func NewQARecordHandler(client *ent.Client) *QARecordHandler {
	return &QARecordHandler{client: client}
}

// CreateQARecordRequest 创建问答请求
type CreateQARecordRequest struct {
	Question string `json:"question"`
}

// UpdateQARecordRequest 更新问答请求
type UpdateQARecordRequest struct {
	AnswerUser1 string `json:"answer_user1"`
	AnswerUser2 string `json:"answer_user2"`
}

// GetQARecords 获取所有未删除的问答
func (h *QARecordHandler) GetQARecords(c *fiber.Ctx) error {
	ctx := context.Background()
	qaRecords, err := h.client.QARecord.Query().
		Where(qarecord.DeletedAtIsNil()).
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取问答列表失败")
	}

	return models.Success(c, qaRecords)
}

// GetQARecord 获取单个问答
func (h *QARecordHandler) GetQARecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的问答ID")
	}

	qaRecord, err := h.client.QARecord.Get(ctx, id)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "问答不存在")
		}
		return models.InternalServerError(c, "获取问答失败")
	}

	return models.Success(c, qaRecord)
}

// CreateQARecord 创建问答
func (h *QARecordHandler) CreateQARecord(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateQARecordRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.Question == "" {
		return models.BadRequest(c, "问题不能为空")
	}

	qaRecord, err := h.client.QARecord.
		Create().
		SetQuestion(req.Question).
		Save(ctx)

	if err != nil {
		return models.InternalServerError(c, "创建问答失败")
	}

	return models.SuccessWithMessage(c, "创建成功", qaRecord)
}

// UpdateQARecord 更新问答（提交答案）
func (h *QARecordHandler) UpdateQARecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的问答ID")
	}

	var req UpdateQARecordRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	builder := h.client.QARecord.UpdateOneID(id)

	if req.AnswerUser1 != "" {
		builder.SetAnswerUser1(req.AnswerUser1)
	}

	if req.AnswerUser2 != "" {
		builder.SetAnswerUser2(req.AnswerUser2)
	}

	qaRecord, err := builder.Save(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "问答不存在")
		}
		return models.InternalServerError(c, "更新问答失败")
	}

	return models.SuccessWithMessage(c, "提交答案成功", qaRecord)
}

// DeleteQARecord 软删除问答
func (h *QARecordHandler) DeleteQARecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的问答ID")
	}

	// 软删除：设置 deleted_at 为当前时间
	now := time.Now()
	_, err = h.client.QARecord.UpdateOneID(id).
		SetDeletedAt(now).
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "问答不存在")
		}
		return models.InternalServerError(c, "删除问答失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}

// GetDeletedQARecords 获取所有已删除的问答（回收站）
func (h *QARecordHandler) GetDeletedQARecords(c *fiber.Ctx) error {
	ctx := context.Background()
	qaRecords, err := h.client.QARecord.Query().
		Where(qarecord.DeletedAtNotNil()).
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取已删除问答失败")
	}

	return models.Success(c, qaRecords)
}

// RestoreQARecord 恢复已删除的问答
func (h *QARecordHandler) RestoreQARecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的问答ID")
	}

	// 恢复：清空 deleted_at
	_, err = h.client.QARecord.UpdateOneID(id).
		ClearDeletedAt().
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "问答不存在")
		}
		return models.InternalServerError(c, "恢复问答失败")
	}

	return models.SuccessWithMessage(c, "恢复成功", nil)
}

// PermanentDeleteQARecord 永久删除问答
func (h *QARecordHandler) PermanentDeleteQARecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的问答ID")
	}

	err = h.client.QARecord.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "问答不存在")
		}
		return models.InternalServerError(c, "永久删除问答失败")
	}

	return models.SuccessWithMessage(c, "永久删除成功", nil)
}
